<?php
namespace app\beautiful\logic;
use app\beautiful\model\partner\PartnerSettingModel;
use app\beautiful\model\PartnerModel;
use app\beautiful\model\member\MemberModel;
use app\beautiful\model\partner\PartnerCommissionModel;
class PartnerLogic {
    private  $setting;
    private  $shopId;
    public function __construct($shopId) {
        $this->setting = PartnerSettingModel::where('shop_id',$shopId)->find();
        $this->shopId = $shopId;
    }

    /**
     * @params $memberId,$money 
     * @return  bool 
     */
    public function  commission($memberId,$money){
        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        if($money <= 0) return false;
        $pid  = $mid = 0; $mobile = '';
        if(is_numeric($memberId)){
            $member = MemberModel::find($memberId);
            if(null === $member) return false;
            $pid = $member->pid;
            $mid = $memberId;
        }else{
            $pid = $memberId->pid;
            $mid = $memberId->member_id;
        }
        if(empty($pid)) return false;
        $pmemberModel = new MemberModel();
        if(null === $pmember = $pmemberModel->find($pid)) return false;
        $partner = PartnerModel::where([
            ['mobile','=',$pmember->mobile],
            ['shop_id','=', $this->shopId],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;
        
        // 是否有上一级别
        $grandpa_partner = [];
        if(!empty($pmember->pid)) {
            $grandpa  = $pmemberModel->where([
                ['member_id','=',$pmember->pid]
            ])->find();
            if($grandpa) {
                $grandpa_partner = PartnerModel::where([
                    ['mobile','=',$grandpa->mobile],
                    ['shop_id','=', $this->shopId],
                    ['status','=',1],
                    ['is_delete','=',0]
                ])->find();
            }
        }
        // var_dump($grandpa_partner);exit;
        switch($partner->role_id){
            case 1: //股东
                return  $this->shareholderCommission($partner, $mid, $money,$grandpa_partner);
                break;
            case 2://员工
                return  $this->staffCommission($partner, $mid, $money,$grandpa_partner);
                break;
            case 3://会员
                return  $this->memberCommission($partner, $mid, $money,$grandpa_partner);
                break;
            case 4://自定义
                return  $this->customCommission($partner, $mid, $money,$grandpa_partner);
                break;
        }
        return true;
    }
    //员工业绩
    private function staffCommission($partner,$mid,$money,$grandpa_partner = []){
        if(empty($this->setting->commission_data)) return false;
        $month = date('Y-m',time());
        $sum = PartnerCommissionModel::where([
            ['shop_id','=', $this->shopId],
            ['partner_id','=',$partner->partner_id],
            ['month','=',$month]
        ])->sum('monetary');
        $nowMoney = round(($sum*100 + $money * 100)/100,2);
        //start_achievement
        $commissionRate = 0;
        foreach($this->setting->commission_data as $val){
            if($nowMoney >= $val['start_achievement'] && $val['commission'] >= $commissionRate){
                $commissionRate = $val['commission'];
            }
        }
     
        if(empty($commissionRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = 0; //不可提现
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'level'      => 1,
        ]);
        if($grandpa_partner) {
            if(null === $pmember = MemberModel::where([
                    ['shop_id','=',$this->shopId],
                    ['mobile','=',$grandpa_partner->mobile]
                ])->find()){
                return false;
            }
            
            $grandpa_sum = PartnerCommissionModel::where([
                ['shop_id','=', $this->shopId],
                ['partner_id','=',$partner->partner_id],
                ['month','=',$month]
            ])->sum('monetary');
            
            $grandpa_nowMoney = round(($sum*100 + $money * 100)/100,2);
            
            $secondCommissionRate = 0;
            foreach($this->setting->commission_data as $val){
                if($grandpa_nowMoney >= $val['start_achievement'] && $val['second_commission'] >= $secondCommissionRate){
                    $secondCommissionRate = $val['second_commission'];
                }
            }
            if(empty($secondCommissionRate)) return false;
            if($secondCommissionRate <= 0 || $secondCommissionRate >= 100) return false;
            $commissionSecond = round(($money * $secondCommissionRate)/100,2); //保留2位小数
            if($commissionSecond < 0.01) return false; 
            $PartnerCommissionModel = new PartnerCommissionModel();
            $grandpa_partner->profit = round(($grandpa_partner->profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->withdrawable_profit = round(($grandpa_partner->withdrawable_profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->save();
            $PartnerCommissionModel->save([
                'shop_id'    => $this->shopId,
                'partner_id' => $grandpa_partner->partner_id,
                'member_id'  => $pmember->member_id,
                'month'      => date('Y-m',time()),
                'monetary'   => $money,
                'commission' => $commissionSecond,
                'level'      => 2,
            ]);
        }
        return true;
    }
    //会员推广员业绩
    private function  memberCommission($partner,$mid,$money,$grandpa_partner = []){
        $commissionRate = $this->setting->commission;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = round(($partner->withdrawable_profit *  100  + $commission * 100)/100,2);
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'level'      => 1,
        ]);
        
        if($grandpa_partner) {
            if(null === $pmember = MemberModel::where([
                    ['shop_id','=',$this->shopId],
                    ['mobile','=',$grandpa_partner->mobile]
                ])->find()){
                return false;
            }
            
            
            $secondCommissionRate = $this->setting->second_commission;
            if($secondCommissionRate <= 0 || $secondCommissionRate >= 100) return false;
            $commissionSecond = round(($money * $secondCommissionRate)/100,2); //保留2位小数
            if($commissionSecond < 0.01) return false; 
            $PartnerCommissionModel = new PartnerCommissionModel();
            $grandpa_partner->profit = round(($grandpa_partner->profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->withdrawable_profit = round(($grandpa_partner->withdrawable_profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->save();
            $PartnerCommissionModel->save([
                'shop_id'    => $this->shopId,
                'partner_id' => $grandpa_partner->partner_id,
                'member_id'  => $pmember->member_id,
                'month'      => date('Y-m',time()),
                'monetary'   => $money,
                'commission' => $commissionSecond,
                'level'      => 2,
            ]);
        }
        
        return true;
    }
    //股东业绩
    private function  shareholderCommission($partner,$mid,$money,$grandpa_partner = []){
        $share_capital = $partner->share_capital;
        if(empty($this->setting->dividend_ratio_data)) return false;
        $commissionRate = 0;
        foreach($this->setting->dividend_ratio_data as $val){
            if($val['share_capital'] <= $share_capital && $val['dividend_ratio'] >= $commissionRate){
                $commissionRate =  $val['dividend_ratio'];
            }
        }
        if(empty($commissionRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        $commission   = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false; 
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = round(($partner->withdrawable_profit *  100  + $commission * 100)/100,2);
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'level'      => 1,
        ]);
        if($grandpa_partner) {
            if(null === $pmember = MemberModel::where([
                    ['shop_id','=',$this->shopId],
                    ['mobile','=',$grandpa_partner->mobile]
                ])->find()){
                return false;
            }
            $PartnerCommissionModel = new PartnerCommissionModel();
            $secondCommissionRate = 0;
            foreach($this->setting->dividend_ratio_data as $val){
                if($val['share_capital'] <= $share_capital && $val['second_ratio'] >= $secondCommissionRate){
                    $secondCommissionRate =  $val['second_ratio'];
                }
            }
            if(empty($secondCommissionRate)) return false;
            if($secondCommissionRate <= 0 || $secondCommissionRate >= 100) return false;
            $commission   = round(($money * $secondCommissionRate)/100,2); //保留2位小数
            $grandpa_partner->profit = round(($grandpa_partner->profit *  100  + $commission * 100)/100,2);
            $grandpa_partner->withdrawable_profit = round(($grandpa_partner->withdrawable_profit *  100  + $commission * 100)/100,2);
            $grandpa_partner->save();
            $PartnerCommissionModel->save([
                'shop_id'    => $this->shopId,
                'partner_id' => $grandpa_partner->partner_id,
                'member_id'  => $pmember->member_id,
                'month'      => date('Y-m',time()),
                'monetary'   => $money,
                'commission' => $commission,
                'level'      => 2,
            ]);
        }
        return true;
    }
    // 自定义
    private function customCommission($partner,$mid,$money,$grandpa_partner)
    {
        $commissionRate=$partner->custom_rate;
        $commissionSecondRate=$partner->custom_second_rate;
        if(empty($commissionRate)) return false;
        if(empty($commissionSecondRate)) return false;
        if($commissionRate <= 0 || $commissionRate >= 100) return false;
        if($commissionSecondRate <= 0 || $commissionSecondRate >= 100) return false;
        $commission = round(($money * $commissionRate)/100,2); //保留2位小数
        if($commission < 0.01) return false;
        $commissionSecond = round(($money * $commissionSecondRate)/100,2); //保留2位小数
        if($commission < 0.01) return false;
        if($commissionSecond < 0.01) return false;
        $partner->profit = round(($partner->profit *  100  + $commission * 100)/100,2);
        $partner->withdrawable_profit = 0; //不可提现
        $partner->save();
        $PartnerCommissionModel = new PartnerCommissionModel();
        $PartnerCommissionModel->save([
            'shop_id'    => $this->shopId,
            'partner_id' => $partner->partner_id,
            'member_id'  => $mid,
            'month'      => date('Y-m',time()),
            'monetary'   => $money,
            'commission' => $commission,
            'level'      => 1,
        ]);
        if($grandpa_partner) {
            if(null === $pmember = MemberModel::where([
                    ['shop_id','=',$this->shopId],
                    ['mobile','=',$grandpa_partner->mobile]
                ])->find()){
                return false;
            }
            
            $PartnerCommissionModel = new PartnerCommissionModel();
            $grandpa_partner->profit = round(($grandpa_partner->profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->withdrawable_profit = round(($grandpa_partner->withdrawable_profit *  100  + $commissionSecond * 100)/100,2);
            $grandpa_partner->save();
            $PartnerCommissionModel->save([
                'shop_id'    => $this->shopId,
                'partner_id' => $grandpa_partner->partner_id,
                'member_id'  => $pmember->member_id,
                'month'      => date('Y-m',time()),
                'monetary'   => $money,
                'commission' => $commissionSecond,
                'level'      => 2,
            ]);
        }
        return true;
    }
    
    
    /**
     * @params  $memberId,$pid, $isNew 是否是新用户
     * @return  bool  
     */
    public function bindPartner($memberId,$pid,$isNew = true){
        if(empty($pid)) return false;
        if(null === $this->setting) return false; //如果setting 不正确就直接返回 不做任何处理
        $MemberModel = new MemberModel();
        if(null === $member = $MemberModel->find($memberId)) return false;
        if($member->pid != 0) return false; //父级ID 不为空
        
        if(null === $pmember = MemberModel::find($pid)) return false;
        
        $partner = PartnerModel::where([
            ['shop_id','=',$this->shopId],
            ['mobile','=',$pmember->mobile],
            ['status','=',1],
            ['is_delete','=',0]
        ])->find();
        if(null === $partner) return false;
        
        $partner_setting_status=false;
        if($partner->role_id==1 && $this->setting->is_bind_shareholder==1) $partner_setting_status=true;
        if($partner->role_id==2 &&  $this->setting->is_bind_employee==1) $partner_setting_status=true;
        if($partner->role_id==3) $partner_setting_status=true;
        if($partner->role_id==4) $partner_setting_status=true;
        if($isNew || $partner_setting_status){
            $member->pid=$pid;
            $member->save();
            return  true;
        }
        return false;
    }
    
    // 将注册会员转换成会员合伙人
    public function memberPartner($mobile,$member_name = '未设置') {
        // 当前用户是否已经是会员合伙人
        $memberPartner = PartnerModel::where([
            ['shop_id','=',$this->shopId],
            ['is_delete','=',0],
            ['mobile','=',$mobile],
        ])->find();
        if(!empty($memberPartner)) {
            return false;
        }
        // 设置会员合伙人属性
        $partner = new PartnerModel();
        $partner->shop_id = $this->shopId;
        $partner->role_id = 3;
        $partner->name    = !empty($member_name) ? $member_name:'未设置';
        $partner->mobile  = $mobile;
        $partner->save();
    }
    
}